package com.zsrt.scott;

import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ScottClassPathXmlApplicationContext {
	
	
	
	
	private Map<String, Object> container = new HashMap<String, Object>();
	
	
	public ScottClassPathXmlApplicationContext(){}
	
	
	public  ScottClassPathXmlApplicationContext(String path){
		
		
		
        try {
        	//1 根据传过来的路径  使用dom4j解析xml
    		SAXReader reader = new SAXReader();  
            //读取文件 转换成Document  
			Document document = reader.read(new File("src/main/resources/"+path));
			
			System.out.println(document.getClass().getName());
			
			//拿到根节点 beans
			Element root = document.getRootElement();
			
			
			List child = root.elements("bean");
			
			
			
			
			System.out.println(child.size());
			
			
			//循环xml后得到的所有的对象都应该放在1个容器中 方便以后拿  Map
			for(Object  obj : child){
				
				Element  bean = (Element)obj;
				
				String id = bean.attributeValue("id");
				
				//com.zsrt.scott.entity.Student
				String clazz = bean.attributeValue("class");
				
				System.out.println("id="+id+",class="+clazz);
				
				//用反射把字符串转化为对应的对象
				Class  clss = Class.forName(clazz);
				Object stu = clss.newInstance();
				
				container.put(id, stu);
				
				
				//从bean中拿到 id和name属性
				
				
				List ps = bean.elements("property");
				
				
				for( Object p :ps){
					Element property =(Element)p;
					
					
					//age
					String name = property.attributeValue("name");
					
					
					//17
					String value = property.attributeValue("value");
					
					
					//利用反射调用对象的方法  
					
					//1 根据属性名称 age 得到这个属性的类型 Integer
					
					Field[] fs = clss.getDeclaredFields();
					
					
					for(Field field : fs){
						
						String fname = field.getName();
						Class<?> ftype = field.getType();
						
						System.err.println("ftype"+ftype.getName());
						
						
						
						if(fname.equals(name)){
							
							//如果是整形 需要强转
							if(ftype.getName().equals("java.lang.Integer")){
								field.setAccessible(true);
								field.set(stu, Integer.parseInt(value));
							}else{
								field.setAccessible(true);
								field.set(stu, value);
							}
							
							
						}
						
						
						
					}
					
					
					
					//2 给这个属性赋值
					
					
					
					
				}
				
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	
	
	public Object getBean(String id){
		
		return container.get(id);
	}
}
